<?php

namespace DreamCat\FrameCore\Cases;

use DreamCat\FrameCore\ConfigReaderImpl;
use DreamCat\FrameCore\FpmEntrance;
use DreamCat\FrameCore\HelperClass\TestEmit;
use PHPUnit\Framework\TestCase;
use Psr\Http\Message\ResponseInterface;
use Zend\Diactoros\Response\TextResponse;
use Zend\HttpHandlerRunner\Emitter\EmitterInterface;

/**
 * 测试配置有问题的场景
 * @author vijay
 */
class ConfigErrorTest extends TestCase
{
    /** @var string 配置路径 */
    private $configPath;

    /**
     * 测试空路由配置
     * @return void
     */
    public function testEmptyRouter()
    {
        # 建立基境
        $rootPath = realpath(__DIR__ . "/../../../");
        if (!is_dir($rootPath . "/cache/configs/")) {
            mkdir($rootPath . "/cache/configs/", 0777, true);
        }

        $this->configPath = $rootPath . "/cache/configs/config.php";
        if (file_exists($this->configPath)) {
            rename($this->configPath, $this->configPath . ".bak");
        }
        $config = [
            "router" => [],
            "beans" => [EmitterInterface::class => TestEmit::class],
        ];
        file_put_contents($this->configPath, "<?php\nreturn " . var_export($config, true) . ";");

        # 调用启用入口
        FpmEntrance::startWithConfigReader(new ConfigReaderImpl($rootPath));

        # 对比数据
        /** @var ResponseInterface $response */
        $response = TestEmit::$lastResponse;

        self::assertEquals(TextResponse::class, get_class($response), "返回值类型不一");
        self::assertEquals(404, $response->getStatusCode(), "状态码不正确");
        self::assertEquals("not found", $response->getBody()->getContents(), "返回文本不正确");
    }

    /**
     * 取消基境
     * @return void
     */
    public function tearDown(): void
    {
        parent::tearDown();
        # 恢复基境
        if (file_exists($this->configPath . ".bak")) {
            rename($this->configPath . ".bak", $this->configPath);
        } else {
            unlink($this->configPath);
        }
    }
}

# end of file
